package cn.czh;

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.Test;
import org.omg.PortableServer.ForwardRequest;

import java.util.HashMap;

public class EsTest {

    // ES新增
    @Test
    public void testAdd() throws Exception{
        //1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
       /* //2.指定索引、类型、id得到新增对象
        IndexRequestBuilder builder = client.prepareIndex("pethome", "pet", "1");
        //3.创建要新增的数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",1L);
        map.put("name","白狐");
        map.put("age",8);
        map.put("sex",1);
        //4.进行新增
        IndexRequestBuilder source = builder.setSource(map);
        //5.获得设置结果
        IndexResponse response = source.get();
        System.out.println(response);*/

        //3.创建要新增的数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("id",1L);
        map.put("name","白狐");
        map.put("age",8);
        map.put("sex",1);

        IndexResponse response = client.prepareIndex("pethome", "pet", "1").setSource(map).get();
        System.out.println(response);
        client.close();
    }


    //获取
    @Test
    public void testGet() throws Exception{
        //1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        //2.指定索引、类型、id得到查询对象
        GetRequestBuilder builder = client.prepareGet("pethome", "pet", "1");
        System.out.println(builder.get().getSource());
    }


    //更新  -- 局部修改
    @Test
    public void testUpdate() throws Exception{
        //1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        //2.指定索引、类型、id得到更新对象
        UpdateRequestBuilder builder = client.prepareUpdate("pethome", "pet", "1");
        //3.创建要更新的数据
        HashMap<String, Object> map = new HashMap<>();
        map.put("name","妖狐");
        UpdateResponse updateResponse = builder.setDoc(map).get();
        System.out.println(updateResponse);
    }


    //删除
    @Test
    public void testDelete() throws Exception{
        //1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        //2.指定索引、类型、id得到删除对象
        DeleteRequestBuilder builder = client.prepareDelete("pethome", "pet", "1");
        //拿到删除结果
        System.out.println(builder.get());
    }

    /**
     * - 查询用户表
     * - name包含：我在源码
     *
     * - age在1~12之间
     * - sex=1
     *
     * - 每页大小2
     * - 从2页开始查
     * - 按照age倒序
     *
     * @throws Exception
     */
    @Test
    public void test1() throws Exception{
        // 1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        // 2. 设置要条件查询的索引 -- 得到搜索对象
        SearchRequestBuilder builder = client.prepareSearch("pethome");
        //3.设置搜索条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        boolQuery.must(QueryBuilders.matchQuery("name","我在源码"));

        boolQuery.filter(QueryBuilders.termQuery("sex", 1))
                .filter(QueryBuilders.rangeQuery("age").gte(1).lte(12));

        builder.setQuery(boolQuery); //一个方法要求传一个接口，有几种方式，ID越高越推荐使用：1、匿名内部类 2、实现类 3、接口对应的工具类
        //4.设置分页排序
        builder.setFrom(2); //（当前页-1）*每页展示条数
        builder.setSize(2); //每页展示8条数据
        builder.addSort("age", SortOrder.DESC);
        SearchResponse response = builder.get();
        SearchHit[] hits = response.getHits().getHits();
        for (SearchHit hit : hits) {
            System.out.println(hit.getSourceAsMap());
        }
    }



    /**
     * @Description: 批量添加数据
     * @Author: Director
     * @Date: 2022/7/23 0:02
     * @return: void
     **/
    @Test
    public void testBatch() throws Exception {
        // 1.获取ES连接
        TransportClient client = ESClientUtil.getClient();
        // 2.创建批量操作对象
        BulkRequestBuilder bulk = client.prepareBulk();
        // 3.批量创建文档，放入批量操作对象中
        for (int i = 2; i < 100; i++) {
            IndexRequestBuilder builder = client.prepareIndex("pethome", "user", i + "").setSource(
                    XContentFactory.jsonBuilder()
                            .startObject()
                            .field("id", i - 1)
                            .field("name", "我在源码学习Java!" + i)
                            .field("age", i - 1)
                            .field("sex", i%2)
                            .endObject()
            );
            BulkResponse result = bulk.add(builder).get();
            System.out.println(result.status());
        }
        // 4.关闭连接
        client.close();
    }
}
